package org.fb.service;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.fb.dto.RpcRequest;
import org.fb.dto.RpcResponse;
import org.fb.handler.UserServiceHandler;
import org.fb.utils.JSONSerializer;
import org.fb.utils.RpcDecoder;
import org.fb.utils.RpcEncoder;
import org.springframework.stereotype.Service;

/**
 * @author fanbo@imoran.net
 * @date 2021/2/6 17:32
 */
@Service("userService")
public class UserServiceImpl implements IUserService {

    /**
     * 将来客户单要远程调用的方法
     */
    @Override
    public RpcResponse sayHello(String msg) {
        System.out.println("Received from client:  " + msg);
        RpcResponse rpcResponse = new RpcResponse();
        rpcResponse.setResultMsg("服务器收到client数据 : " + msg);
        rpcResponse.setResult("success");
        return rpcResponse;
    }

    /**
     * 创建一个方法启动服务器
     */
    public static void startServer(String ip, int port) throws InterruptedException {
        //1.创建两个线程池对象
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();

        //2.创建服务端的启动引导对象
        ServerBootstrap serverBootstrap = new ServerBootstrap();

        //3.配置启动引导对象
        serverBootstrap.group(bossGroup, workGroup)
                //设置通道为NIO
                .channel(NioServerSocketChannel.class)
                //创建监听channel
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        //获取管道对象
                        ChannelPipeline pipeline = nioSocketChannel.pipeline();
                        //给管道对象pipeLine 设置编码
                        pipeline.addLast(new RpcEncoder(RpcResponse.class, new JSONSerializer()));
                        pipeline.addLast(new RpcDecoder(RpcRequest.class, new JSONSerializer()));

                        //把我们自定义的ChannelHander添加到通道中
                        pipeline.addLast(new UserServiceHandler());
                    }
                });

        //4.绑定端口
        serverBootstrap.bind(ip, port).sync();
    }
}

